﻿namespace IntellectShop.Common
{
	using System.Collections;
	using System.Collections.Generic;
	using System.Linq;
	using System.Transactions;

	public partial class TagsSet
	{
		public static TagsSet GetFavoritesTags(IEnumerable commodityList)
		{
			var uniqIDs = (
				from c in commodityList.Cast<Common.Commodity>()
				select c.CommodityID).Distinct();

			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var query =
					from t in dataContext.TagsSets
					where uniqIDs.Contains(t.CommodityID)
					group t by new
					{
						t.Tag,
						t.SingleTag
					} into g
					orderby g.Key.SingleTag.SortingID descending, g.Key.Tag
					select new
					{
						g.Key.Tag,
						TagsCount = g.Count()
					};

				TagsSet result = new TagsSet();
				foreach (var item in query.OrderByDescending(x => x.TagsCount))
				{
					result.Add(item.Tag);
				}

				return result;
			}
		}

		public static TagsSet RetrieveByCommodityID(int commodityID)
		{
			using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
			{
				var query =
							from tagsSet in dataContext.TagsSets
							where tagsSet.CommodityID == commodityID
							orderby tagsSet.SingleTag.SortingID descending, tagsSet.Tag
							select tagsSet.Tag;

				TagsSet set = new TagsSet(commodityID);
				foreach (var tag in query)
				{
					set.Add(tag);
				}

				return set;
			}
		}

		public void Save()
		{
			using (TransactionScope trans = new TransactionScope())
			{
				using (DB.IntellectShopDataContext dataContext = new DB.IntellectShopDataContext(Common.Globals.ConnectionString))
				{
					IEnumerable<string> uniqTags = this.Distinct();
					//создаем одиночный тег, если его не было
					foreach (var tag in uniqTags)
					{
						var singleTagDB = new DB.SingleTag
						{
							Tag = tag
						};

						if (!dataContext.SingleTags.Contains(singleTagDB))
						{
							dataContext.SingleTags.InsertOnSubmit(singleTagDB);
						}
					}

					dataContext.SubmitChanges();

					//добавим теги для данного товара
					foreach (var tag in uniqTags)
					{
						var tagsSetsDB = new DB.TagsSet
						{
							CommodityID = this.CommodityID,
							Tag = tag
						};

						if (!dataContext.TagsSets.Contains(tagsSetsDB))
						{
							dataContext.TagsSets.InsertOnSubmit(tagsSetsDB);
						}
					}

					dataContext.SubmitChanges();

					//удалим неиспользуемые теги для данного товара
					var tagsSetDB =
						from tags in dataContext.TagsSets
						where tags.CommodityID == this.CommodityID && !uniqTags.Contains(tags.Tag)
						select tags;
					dataContext.TagsSets.DeleteAllOnSubmit(tagsSetDB);
					dataContext.SubmitChanges();

					trans.Complete();
				}
			}
		}
	}
}
